<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Http\Controllers;

use App\Enums\HideOrShowEnum;
use App\Exceptions\ApiException;
use App\Format\ArticleFormat;
use App\Http\Requests\CreateArticleRequest;
use App\Http\Requests\GetArticleRequest;
use App\Services\AdminAuthService;
use App\Services\ArticleService;
use App\Services\UserService;
use App\Services\ZhanXinPublicArticleService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;

class ArticleController extends Controller
{
    protected $articleService;

    protected $adminAuthService;

    public function __construct(ArticleService $articleService, AdminAuthService $adminAuthService)
    {
        $this->articleService = $articleService;
        $this->adminAuthService = $adminAuthService;
    }

    public function getListByType(GetArticleRequest $getArticleRequest)
    {
        $type = $getArticleRequest->input('type');
        $page = $getArticleRequest->input('page', 1);
        $pageSize = $getArticleRequest->input('page_size', 10);
        $userId = $getArticleRequest->input('user_id');
        $token = $getArticleRequest->input('token');
        $isAdmin = $this->checkIsAdmin($userId, $token);
        $isAdmin && $this->checkShowArticleList($userId, $token, $type);
        $search = [];
        if ($getArticleRequest->input('start_date')) {
            $search['start_date'] = $getArticleRequest->input('start_date');
        }
        if ($getArticleRequest->input('end_date')) {
            $search['end_date'] = $getArticleRequest->input('end_date');
        }
        if ($getArticleRequest->input('title')) {
            $search['title'] = $getArticleRequest->input('title');
        }
        $orderColumn = $getArticleRequest->input('order_column', '');
        $orderCType = $getArticleRequest->input('order_type', '');
        $list = $this->articleService->getArticleListByType($type, $page, $pageSize, $orderColumn, $orderCType, $search, $isAdmin);
        return renderSuccessJson($list);
    }

    public function getArticleDetail(Request $request)
    {
        $id = $request->input('id', 1);
        $detail = $this->articleService->getArticleDeatil($id);
        return renderSuccessJson($detail);
    }

    public function getZhanxinArticles(Request $getArticleRequest, ZhanXinPublicArticleService $zhanXinPublicArticleService)
    {
        $page = $getArticleRequest->input('page', 1);
        $pageSize = $getArticleRequest->input('page_size', 8);
        $res = $zhanXinPublicArticleService->getZhanxinArticlesList($page, $pageSize);
        return renderSuccessJson($res);
    }

    public function getVillagePromises()
    {
        $article = $this->articleService->findVillagePromise();
        return renderSuccessJson($article);
    }

    public function getScore()
    {
        $article = $this->articleService->findScore();
        return renderSuccessJson($article);
    }

    public function getCompanyScore()
    {
        $article = $this->articleService->findCompanyScore();

        return renderSuccessJson($article);
    }

    public function create(CreateArticleRequest $createArticleRequest)
    {
        $format = new ArticleFormat($createArticleRequest->all());
        $userId = $createArticleRequest->input('user_id');
        if (! $this->adminAuthService->checkSuperAdmin($userId)) {
            if (! $this->articleService->checkArticleTypeAuth($userId, 'create', $format->getType())) {
                return renderErrorJson(1, '权限不足');
            }
        }
        $this->articleService->create($format);
        return renderSuccessJson();
    }

    public function update(Request $request)
    {
        $id = $request->input('id');
        $userId = $request->input('user_id');
        if (empty($id)) {
            throw new ApiException('缺少参数', 1);
        }
        $format = new ArticleFormat($request->all());
        if (! $this->adminAuthService->checkSuperAdmin($userId)) {
            if (! $this->articleService->checkArticleTypeAuth($userId, 'update', $format->getType())) {
                return renderErrorJson(1, '权限不足');
            }
        }
        $this->articleService->update($format);
        return renderSuccessJson();
    }

    public function delete(Request $request)
    {
        $id = $request->input('id');
        $userId = $request->input('user_id');
        if (empty($id)) {
            throw new ApiException('缺少参数', 1);
        }
        $articleType = $this->articleService->getArticleType($id);
        if (! $this->adminAuthService->checkSuperAdmin($userId)) {
            if (! $this->articleService->checkArticleTypeAuth($userId, 'update', $articleType)) {
                return renderErrorJson(1, '权限不足');
            }
        }
        $this->articleService->delete($id);
        return renderSuccessJson();
    }

    public function getLookofVillage()
    {
        return renderSuccessJson(config('lookof_village'));
    }

    public function downloadArticle(Request $request)
    {
        $id = $request->input('id');
        $fileName = $this->articleService->download($id);
        return Storage::download($fileName);
    }

    public function getSkipNum(ZhanXinPublicArticleService $zhanXinPublicArticleService)
    {
        $skipNum = $zhanXinPublicArticleService->getSkipNum();
        return renderSuccessJson([
            'skip_num' => $skipNum,
        ]);
    }

    public function setSkipNum(ZhanXinPublicArticleService $zhanXinPublicArticleService, Request $request)
    {
        $skipNum = $request->input('skip_num');
        $zhanXinPublicArticleService->setSkipNum($skipNum);
        return renderSuccessJson();
    }

    public function hideOrShow(Request $request)
    {
        $id = $request->input('id');
        $is_hide = $request->input('is_hide');
        if (empty($id)) {
            throw new ApiException('缺少参数', 1);
        }
        if (! in_array($is_hide, [HideOrShowEnum::HIDE, HideOrShowEnum::SHOW])) {
            throw new ApiException('非法参数', 1);
        }
        $this->articleService->hideOrShow($id, $is_hide);
        return renderSuccessJson();
    }

    private function checkShowArticleList($userId, $token, int $articleType)
    {
        if (! $this->adminAuthService->checkSuperAdmin($userId)) {
            if (! $this->articleService->checkArticleTypeAuth($userId, 'select', $articleType)) {
                throw new ApiException('权限不足', 1);
            }
        }
    }

    private function checkIsAdmin($userId, $token)
    {
        if (empty($userId) || empty($token)) {
            return false;
        }
        $adminUserTokenKey = sprintf(UserService::ADMIN_USER_TOKEN_KEY, $userId);
        $redisToken = Redis::connection()->get($adminUserTokenKey);
        if ($redisToken != $token) {
            return false;
        }
        return true;
    }
}
